import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:umeng_push_demo/model/push_message_dao.dart';
import 'package:umeng_push_demo/model/push_message_model.dart';
import 'package:umeng_push_demo/model/push_manager.dart';

/// FileName AppController
///
/// @Author 陈晓星
/// @Date 2024/10/28 08:50
///
/// @Description TODO

class AppController extends GetxController {
  final alias = ''.obs;
  final tag = ''.obs;
  final deviceToken = ''.obs;
  final messageList = RxList<PushMessageModel>();

  @override
  void onInit() {
    super.onInit();
    _initialValueFromLocal();
  }

  /// 初始化，从本地读取标签和别名
  Future<void> _initialValueFromLocal() async {
    alias.value = (await PushManagerSP.getAliasLocal()) ?? '';
    tag.value = (await PushManagerSP.getTagLocal()) ?? '';
    await reloadMessagesFromDB();
  }

  /// 新增消息
  Future<void> insertMessage(PushMessageModel model) async {
    messageList.insert(0, model);
    await PushMessageDao.insert(model);
  }

  /// 从数据库中读取消息列表
  Future<void> reloadMessagesFromDB() async {
    List<PushMessageModel>? list = await PushMessageDao.queryAll();
    messageList.value = list ?? [];
  }

  /// 删除所有消息
  Future<void> deleteAllMessages() async {
    bool isDelete = await PushMessageDao.deleteAll();
    if (isDelete) {
      messageList.clear();
    }
  }
}